﻿using System;
using System.Text;
using System.Data;
using System.Collections.Generic;
using WinnerCMS.Common;
using EntityFramework.Extensions;
using WinnerCMS.Model;

using System.Linq;
namespace WinnerCMS.Data
{
    /// <summary>
    /// LogDal 的摘要说明。
    /// </summary>
    public class LogDal
    {
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="model"></param>
        public void Add(Log model)
        {
            using (Entities db = new Entities())
            {
                db.Logs.Add(model);
                db.SaveChangesAsync().Wait();
            }

        }
        /// <summary>
        /// 删除日志
        /// </summary>
        /// <param name="ids"></param>
        public void Delete(int[] ids)
        {
            using (Entities db = new Entities())
            {
                db.Logs.Where(x => ids.Contains(x.Id)).Delete();
                db.SaveChangesAsync().Wait();
            }
        }
        /// <summary>
        /// 清空日志
        /// </summary>
        public void Clear()
        {
            using (Entities db = new Entities())
            {
                db.Database.ExecuteSqlCommand("Truncate table CMS_Logs");
            }
        }

        /// <summary>
        /// 显示日志类型Tab
        /// </summary>
        /// <returns></returns>
        public IList<Log> GroupBy()
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Logs
                        where !x.Deleted
                        group x by x.Type into g
                        select g.Key;

                return q.ToList().Select(x => new Log { Type = x }).ToList();
            }
        }
        /// <summary>
        /// 绑定分页数据
        /// </summary>
        /// <param name="deleted"></param>
        /// <param name="type"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Log> BindList(bool deleted, string type, PagingParam pp)
        {
            using (Entities db = new Entities())
            {
                var query = from x in db.Logs
                            where !x.Deleted  && (x.Type == type || type == null)
                            select x;
                pp.RecordCount = query.Count();

                return query.OrderByDescending(x => x.Id).Skip(pp.Skip).Take(pp.PageSize).ToList();
            }
        }
    }
}